package com.ruoyi.web.controller.smy;

import cn.hutool.core.collection.CollectionUtil;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserType;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.smy.MallGoods;
import com.ruoyi.common.core.domain.smy.SecurityWebUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.dto.OptDto;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.smy.IMallGoodsService;
import com.ruoyi.system.service.smy.ISecurityWebUserService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping(value = "/smy/mallGoods")
public class MallGoodsController extends BaseController {
	@Resource
	private IMallGoodsService mallGoodsService;

	@Resource
	private ISysRoleService roleService;

	@Resource
	private ISecurityWebUserService webUserService;

	@PreAuthorize("@ss.hasPermi('smy:goods:list')")
	@GetMapping("/list")
	public TableDataInfo list(MallGoods mallGoods) {
		SysUser user = SecurityUtils.getLoginUser().getUser();
		//普通商家用户只显示自身商家的商品信息
		if(roleService.checkHaveRole(user.getRoles(),UserType.COMMON_MERCHANT)){
			SecurityWebUser queryDto = new SecurityWebUser();
			queryDto.setMobile(user.getPhonenumber());
			queryDto.setRoleId(4L);
			List<SecurityWebUser> webUserList = webUserService.selectSecurityWebUserList(queryDto);
			if(CollectionUtil.isNotEmpty(webUserList)){
				SecurityWebUser merchant = webUserList.get(0);
				mallGoods.setMerchantId(merchant.getId());
			}
		}
		startPage();
		List<MallGoods> list = mallGoodsService.selectMallGoodsPage(mallGoods);
		return getDataTable(list);
	}

	@PreAuthorize("@ss.hasPermi('smy:goods:export')")
	@Log(title = "【请填写功能名称】", businessType = BusinessType.EXPORT)
	@PostMapping("/export")
	public void export(HttpServletResponse response, MallGoods mallGoods) {
		List<MallGoods> list = mallGoodsService.selectMallGoodsList(mallGoods);
		ExcelUtil<MallGoods> util = new ExcelUtil<MallGoods>(MallGoods.class);
		util.exportExcel(response, list, "【请填写功能名称】数据");
	}

	@PreAuthorize("@ss.hasPermi('smy:goods:query')")
	@GetMapping(value = "/{id}")
	public AjaxResult getInfo(@PathVariable("id") Long id) {
		return AjaxResult.success(mallGoodsService.selectMallGoodsById(id));
	}

	@PreAuthorize("@ss.hasPermi('smy:goods:add')")
	@Log(title = "【请填写功能名称】", businessType = BusinessType.INSERT)
	@PostMapping
	public AjaxResult add(@RequestBody MallGoods mallGoods) {
		return toAjax(mallGoodsService.insertMallGoods(mallGoods));
	}

	@PreAuthorize("@ss.hasPermi('smy:goods:edit')")
	@Log(title = "【请填写功能名称】", businessType = BusinessType.UPDATE)
	@PutMapping
	public AjaxResult edit(@RequestBody MallGoods mallGoods) {
		return toAjax(mallGoodsService.updateMallGoods(mallGoods));
	}

	@PreAuthorize("@ss.hasPermi('smy:goods:remove')")
	@Log(title = "删除商品", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
	public AjaxResult remove(@PathVariable Long[] ids) {
		return toAjax(mallGoodsService.deleteMallGoodsByIds(ids));
	}

	/**
	 *  批量审核通过/不通过商品记录
	 * @Date 2022/10/12 15:33
	 * @author ZhanCheng.Li
	 * @param optDto
	 * @return
	 */
	@PreAuthorize("@ss.hasPermi('smy:goods:audit')")
	@Log(title = "批量审核通过/不通过商品记录", businessType = BusinessType.UPDATE)
	@PostMapping("/audit")
	public AjaxResult audit(@RequestBody OptDto optDto) {
		try {
			mallGoodsService.auditGoods(optDto);
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error(e.getMessage());
		}
		return AjaxResult.success();
	}


	@PreAuthorize("@ss.hasPermi('smy:goods:status')")
	@Log(title = "批量上架/下架商品", businessType = BusinessType.UPDATE)
	@PostMapping("/changeSellStatus")
	public AjaxResult changeSellStatus(@RequestBody OptDto optDto) {
		try {
			mallGoodsService.changeSellStatus(optDto);
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error(e.getMessage());
		}
		return AjaxResult.success();
	}

	@PreAuthorize("@ss.hasPermi('smy:goods:detail')")
	@Log(title = "查询商品详情", businessType = BusinessType.UPDATE)
	@PostMapping("/getGoodsDetail")
	public AjaxResult getGoodsDetail(@RequestBody MallGoods mallGoods) {
		try {
			return AjaxResult.success(mallGoodsService.getGoodsDetail(mallGoods));
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error(e.getMessage());
		}
	}

	/**
	 *  新增普通商品：
	 *  带SKU，参数，关联商家ID，图片列表
	 * @Date 2022/10/28 16:10
	 * @author ZhanCheng.Li
	 * @param mallGoods
	 * @return
	 */
	@PreAuthorize("@ss.hasPermi('smy:goods:add')")
	@Log(title = "新增普通商品", businessType = BusinessType.INSERT)
	@PostMapping(value = "/addNormalGoods")
	public AjaxResult addNormalGoods(@RequestBody MallGoods mallGoods) {
		//校验新增用户是否为合作商家
		SysUser user = SecurityUtils.getLoginUser().getUser();
		if(roleService.checkHaveRole(user.getRoles(),UserType.COMMON_MERCHANT)){
			SecurityWebUser queryDto = new SecurityWebUser();
			queryDto.setMobile(user.getPhonenumber());
			queryDto.setRoleId(4L);
			List<SecurityWebUser> webUserList = webUserService.selectSecurityWebUserList(queryDto);
			if(CollectionUtil.isNotEmpty(webUserList)){
				SecurityWebUser merchant = webUserList.get(0);
				mallGoods.setMerchantId(merchant.getId());
			}
			mallGoodsService.saveNormalGoods(mallGoods);
		}
		return AjaxResult.success();
	}

}
